using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana.HTN
{
    public sealed class HTN_CompoundTask : HTN_Task
    {
        private List<HTN_Method> _methods = new List<HTN_Method>();
        private HTN_PlanRunner planRunner;

        public bool TryFindPlan(out List<HTN_PrimitiveTask> plan)
        {
            plan = new List<HTN_PrimitiveTask>();
            foreach (var method in _methods)
            {
                if (method.TryFindPlan(out plan)) return true;
            }

            return false;
        }
        
        public override HTNTaskStatus Execute()
        {
            if (status == HTNTaskStatus.Running && planRunner != null)
            {
                return status = planRunner.Execute();
            }
            
            if (!TryFindPlan(out var plan))
            {
                return status = HTNTaskStatus.Failure;
            }
            
            planRunner = new HTN_PlanRunner(plan);
            if (planRunner == null)
            {
                return status = HTNTaskStatus.Failure;
            }

            return status = planRunner.Execute();
        }
    }
}